package user.com.service.impl;

import com.Exception.GlobalException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.constant.ResponseDataConstant;
import com.google.gson.Gson;

import com.responseData.ResponseData;
import com.utils.GenerateNum;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import user.com.aspect.FormatFileURL;
import user.com.entity.Vo.UserLoginVo;
import user.com.mapper.UserMapper;
import user.com.entity.User;
import user.com.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import user.com.entity.Dto.UserLoginDto;
import user.com.utils.MD5Utils;
import user.com.utils.RedisUtils;

import javax.annotation.Resource;
import java.io.File;
import java.nio.file.Files;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xwj
 * @since 2023-11-11
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Value("${file.path}")
    private String filePath;

    @Value("${file.default}")
    private String defaultJpg;

    /**
     * 用户短信登录 未注册则注册
     * @param info 传入参数包括 username 以及 verifyCode
     * @return
     * @throws Exception
     */
    @Override
    @FormatFileURL(value = {"avatar"})
    public UserLoginDto loginWithMsg(UserLoginVo info) throws GlobalException {


        UserLoginDto dto = new UserLoginDto();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        String token = java.util.UUID.randomUUID().toString().replace("-", "");

        String code = (String)RedisUtils.redis.opsForValue().get("code" + info.getUsername());

        if(code == null){
            throw new GlobalException(ResponseData.unusualCustomize(ResponseDataConstant.VERIFY_CODE_TIMEOUT,"验证码已过期"));
        }

        if(!String.valueOf(info.getCode()).equals(code)){
            throw new GlobalException(ResponseData.unusualCustomize(ResponseDataConstant.VERIFY_CODE_ERROR,"验证码错误"));

        }

        User result  = this.getOne(userQueryWrapper.lambda().eq(StringUtil.isNotEmpty(info.getUsername()),
                User::getRegisterEmail, info.getUsername()),false);

        //已有账号直接返回
        if (result != null) {
            BeanUtils.copyProperties(result,dto);
            return dto;
        }

        //没有账号则对其进行注册
        String salt = token.substring(0,6);

        String userId = GenerateNum.generateOrder();

        String defaultAvatar = filePath + userId + "/avatar/default.jpg";
        try{
            //创建默认头像
            File target = new File(defaultAvatar);
            File source = new File(defaultJpg);
            if(!target.exists()){
                target.mkdirs();
            }
            FileUtils.copyFile(source,target);
        }catch (Exception e){
            e.printStackTrace();
            log.info("{}，系统默认头像获取失败",ResponseDataConstant.FAIL);
//            throw new GlobalException(ResponseData.error("系统所需文件缺失"));
        }


        String passwordDB = MD5Utils.inputPassToDBPass("123456", salt);
        User user = User.builder()
                .userId(userId)
                .userName(userId)
                .registerEmail(info.getUsername())
                .password(passwordDB)
                .salt(salt)
                .avatar(defaultAvatar)
                .build();
        this.save(user);

        BeanUtils.copyProperties(user,dto);
        //用户信息保存在redis中
        RedisUtils.redis.opsForValue().set(token, new Gson().toJson(dto),30, TimeUnit.MINUTES);

        return dto;
    }

    /**
     * 以密码登录
     * @param info
     * @return
     * @throws Exception
     */
    @Override
    @FormatFileURL(value = {"avatar"})
    public UserLoginDto loginWithPass(UserLoginVo info) throws GlobalException {

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();

        User result  = this.getOne(userQueryWrapper.lambda().eq(StringUtil.isNotEmpty(info.getUsername()),
                User::getUserName, info.getUsername()),false);

        //用户不存在
        if(result == null){
            throw new GlobalException(ResponseData.unusualCustomize(ResponseDataConstant.USER_USUAL,"账号或者密码错误"));
        }

        String pass = MD5Utils.inputPassToDBPass(info.getPassword(),result.getSalt());

        //账号密码不一致
        if(!pass.equals(result.getPassword())){
            throw new GlobalException(ResponseData.unusualCustomize(ResponseDataConstant.PASS_ERROR,"账号或者密码错误"));
        }

        UserLoginDto dto = new UserLoginDto();

        BeanUtils.copyProperties(result, dto);
        String token = java.util.UUID.randomUUID().toString().replace("-", "");
        dto.setToken(token);
        //用户信息保存在redis中
        RedisUtils.redis.opsForValue().set(token, new Gson().toJson(dto),60, TimeUnit.MINUTES);
        return dto;
    }

    @Override
    @FormatFileURL(value = {"avatar"})
    public UserLoginDto getUserInfoByUid(String userId) throws GlobalException {

        UserLoginDto dto = new UserLoginDto();
        LambdaQueryWrapper<User> eq = new LambdaQueryWrapper<>();
        eq.eq(StringUtils.isNotBlank(userId),User::getUserId,userId);
        User user = this.getOne(eq);

        BeanUtils.copyProperties(user,dto);
        return dto;
    }


}
